// 新建报表
import React from 'react';
import { RouteComponentProps } from 'react-router';
import { connect } from 'react-redux';
import {
	createAnalysePageConfig,
	getAnalysePage,
	getAnalysePageConfig,
	updateAnalysePageConfig,
	publishAnalysePageConfig
} from 'src/services/AnalyseManage';
import EditReportIndex from 'src/pages/AnalyseManage/EditReport/EditReportIndex';
import { message, Modal } from 'antd';
import { setConfig, initState } from 'src/store/editorHistory/actions';
import { ActionCreators } from 'redux-undo';
import { Prompt } from 'react-router-dom';
import { decryptParam } from 'src/libs/paramsEncrypt';

interface IProps {
	setConfig: Function,
	clearHistory: Function,
	pageContentConfig: any,
	match: {
		params: {
			id: string;
			isEdit: string;
			editType: string;	//	 EDIT or PUBLISH
		}
	}
}

class EditReport extends React.PureComponent<RouteComponentProps & IProps> {

	componentDidMount() {
		this.initParams();
	}

	initParams = () => {
		let id = decryptParam( this.props.match.params.id );

		let isEdit = decryptParam( this.props.match.params.isEdit );

		let editType = decryptParam( this.props.match.params.editType );

		this.setState( {
			pageId: id,
			isEdit: isEdit === 'true' ? true : false,
			editType: editType
		} );
		this.initPage( id );
	}

	componentDidUpdate( prevProps: Readonly<RouteComponentProps & IProps>, prevState: Readonly<{}>, snapshot?: any ): void {
		if ( prevProps.match.params.id !== this.props.match.params.id || prevProps.match.params.isEdit !== this.props.match.params.isEdit ) this.initParams();
	}

	// @ts-ignore
	state: any = {
		needSave: false,
		pageId: null,
		/**db**/
		page: {},
		pageConfig: {},
		isEdit: false,		//	是否可编辑
		editType: ''
		/**db-->content-->json**/
		// pageContentConfig: null,
	};

	initPage = async ( id: string ) => {
		let pageResponse = await getAnalysePage( id );
		let pageConfigResponse = await getAnalysePageConfig( { pageId: id, type: this.state.editType } );
		if ( pageResponse.data && pageResponse.data.success ) {
			this.setState( { page: pageResponse.data.data } );
			document.title = pageResponse.data.data.name;
		}
		if ( pageConfigResponse.data && pageConfigResponse.data.success ) {
			this.initPageConfig( pageResponse.data?.data?.type, pageConfigResponse.data.data );
		}
	};
	initPageConfig = ( pageType, pageConfig_: any ) => {
		this.setState( { pageConfig: pageConfig_ } );

		if ( pageConfig_ ) {
			let content = pageConfig_.content;
			let dbConfig = JSON.parse( content );
			this.props.setConfig( dbConfig );
		} else {
			let key = `${ new Date().getTime() }`;
			let pageContentConfig = {
				page: {
					...this.state.page,
					type: pageType,
					key: key,
					name: this.state.page.name,
				},
				children: [],
				layoutConfig: []
			};

			console.log( '新建' );
			this.props.setConfig( pageContentConfig );
			this.saveConfig( null, false );
		}
	};
	saveConfig = async ( values, showMessage=true ) => {
		let pageConfig = this.state.pageConfig;
		// let pageContentConfig = this.state.pageContentConfig;
		let pageContentConfig = this.props.pageContentConfig;
		let content = JSON.stringify( pageContentConfig );
		let response;
		if ( pageConfig && pageConfig.id ) {
			let data = { id: pageConfig.id, content: content };
			response = await updateAnalysePageConfig( data );
		} else {
			let data = { content: content, pageId: this.state.pageId };
			response = await createAnalysePageConfig( data );
		}
		if ( response.data && response.data.success ) {
			if ( showMessage ) {
				message.success( '保存成功' );
			}
		}
		this.setState( { needSave: false } );
	};

	//	发布
	publishConfig = async ( data? ) => {
		console.log( data );
		const res = await publishAnalysePageConfig( {
			...data,
			pageId: this.state.pageId,
			configId: this.state.pageConfig ? this.state.pageConfig.id : '',
			content: JSON.stringify( this.props.pageContentConfig )
		} );
		if ( res.data && res.data.success ) {
			message.success( '发布成功' );
		}
		this.setState( { needSave: false } );
	};

	//	用户操作之后，将操作历史加入redux
	onValuesChange = ( newPageContentConfig ) => {
		console.log( '改变', newPageContentConfig );
		this.props.setConfig( newPageContentConfig );
		this.setState( {
			needSave: true
		} );
	};

	leaveConfirm = ( location, action ) => {
		Modal.confirm( {
			title: '确认离开此页面？',
			okText: '确定',
			cancelText: '取消',
			onOk: () => {
				this.setState( {
					needSave: false
				}, () => {
					console.log( location, action );
					if ( action === 'POP' ) {
						this.props.history.goBack();
					} else if ( action === 'PUSH' ) {
						this.props.history.push( location.pathname );
					} else if ( action === 'REPLACE' ) {
						this.props.history.replace( location.pathname );
					}
				} );

			},
		} );
	}

	render() {
		let pageContentConfig = this.props.pageContentConfig;

		return (
			<div>
				{
					this.state.isEdit && (
						<Prompt when={ this.state.needSave } message={ ( location, action ) => {
							this.leaveConfirm( location, action );
							return false;
						} }/>
					)
				}

				{ pageContentConfig && (
					<EditReportIndex
						pageType={ this.state.page.type }
						pageContentConfig={ pageContentConfig }
						saveConfig={ ( values ) => this.saveConfig( values ) }
						onValuesChange={ ( values ) => this.onValuesChange( values ) }
						isEdit={ this.state.isEdit }
						pageId={ this.state.pageId }
						publishConfig={ this.publishConfig }
						reloadData={this.initParams}
						pageInfo={this.state.page}
					></EditReportIndex>
				) }
			</div>
		);
	}

	componentWillUnmount(): void {
		console.log( '卸载' );
		this.props.setConfig( initState.pageContentConfig );
		this.props.clearHistory();


	}
}

//	映射state到当前组件
const mapStateToProps = ( state ) => {
	return {
		pageContentConfig: state.editorHistory.present.pageContentConfig
	};
};

//	映射dispatch到当前组件
const mapDispatchToProps = ( dispatch ) => {
	return {
		setConfig: ( config ) => {
			dispatch( setConfig( config ) );
		},
		clearHistory: () => dispatch( ActionCreators.clearHistory() )
	};
};

export default connect(
	mapStateToProps,
	mapDispatchToProps
)( EditReport );
